package netty.oven;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static io.netty.handler.codec.http.HttpHeaderNames.*;
import static io.netty.handler.codec.http.HttpResponseStatus.CONTINUE;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

/**
 * @Author zhangtao
 * @create 2021/12/28 11:41
 */
@Slf4j
public class OvenHandler extends ChannelHandlerAdapter {

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        if (msg instanceof HttpRequest) {
            HttpRequest req = (HttpRequest) msg;
            if (HttpHeaderUtil.is100ContinueExpected(req)) {
                ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
            }
            boolean keepAlive = HttpHeaderUtil.isKeepAlive(req);
            FullHttpResponse response = route(req);
            if (!keepAlive) {
                ctx.write(response).addListener(ChannelFutureListener.CLOSE);
            } else {
                response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
                ctx.write(response);
            }
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }

    public FullHttpResponse route(HttpRequest request) {
        String url;
        Map parameterMap = new HashMap<String, List<String>>();
        if (request.uri().indexOf('?') != -1) {
            url = request.uri().substring(0, request.uri().indexOf('?'));
            QueryStringDecoder decoder = new QueryStringDecoder(request.uri());
            parameterMap = decoder.parameters();
        } else {
            url = request.uri();
        }
        String output = "";
        log.info("request {}", request.uri());
        try {
            if (parameterMap.containsKey("haccp")) {
                output = FileUtils.readFileToString(new File("D:\\spring-demo\\tool-example\\src\\main\\java\\netty\\oven\\oven_haccp.xml"),
                        Charset.defaultCharset());
            } else if (parameterMap.containsKey("status")) {
                output = FileUtils.readFileToString(new File("D:\\spring-demo\\tool-example\\src\\main\\java\\netty\\oven\\oven_status.xml"),
                        Charset.defaultCharset());
            } else if (parameterMap.containsKey("cmd")) {
                output = FileUtils.readFileToString(new File("D:\\spring-demo\\tool-example\\src\\main\\java\\netty\\oven\\service.txt"),
                        Charset.defaultCharset());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(output.getBytes()));
        response.headers().set(CONTENT_TYPE, "text/html;charset=UTF-8");
        response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes());
        return response;
    }

}
